package br.com.virtual.base.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Named;

@Named("cpfConverter")
public class CPFConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String valor) {

		String cpf = valor;
		if (valor != null && !valor.equals("")) {
			cpf = valor.replaceAll("\\.", "").replaceAll("\\-", "");
		}

		return cpf;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object valor) {

		String cpf = valor.toString();

		if (cpf != null && cpf.length() == 11) {

			cpf = cpf.substring(0, 3) + "." + cpf.substring(3, 6) + "."
					+ cpf.substring(6, 9) + "-" + cpf.substring(9, 11);
		}
		return cpf;
	}

}
